package com.pray.praymall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.pray.common.to.es.SkuEsModel;
import com.pray.common.utils.R;
import com.pray.praymall.search.config.ElasticSearchConfig;
import com.pray.praymall.search.constant.EsConstant;
import com.pray.praymall.search.feign.ProductFeignService;
import com.pray.praymall.search.service.MallSearchService;
import com.pray.praymall.search.vo.AttrResponseVo;
import com.pray.praymall.search.vo.BrandVo;
import com.pray.praymall.search.vo.SearchParamVo;
import com.pray.praymall.search.vo.SearchResultVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * do something
 *
 * @author 魂悸魄
 * @date 2020/9/15 21:03
 */
@Slf4j
@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Resource
    private RestHighLevelClient client;

    @Resource
    private ProductFeignService productFeignService;

    @Override
    public SearchResultVo search(SearchParamVo searchParamVo) {
        SearchResultVo result = null;
        // 1、准备检索请求
        SearchRequest searchRequest = buildSearchRequest(searchParamVo);
        try {
            // 2、执行检索请求
            SearchResponse response = client.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);
            // 3、分析响应数据封装成我们需要的格式
            result = buildSearchResult(response, searchParamVo);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 构建结果数据
     *
     * @param response es的返回数据
     * @return 构建好的结果
     */
    private SearchResultVo buildSearchResult(SearchResponse response, SearchParamVo paramVo) {
        SearchResultVo result = new SearchResultVo();
        // 1.返回的所有查询到的商品
        SearchHits hits = response.getHits();

        List<SkuEsModel> esModels = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                // ES中检索得到的对象
                SkuEsModel esModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (!StringUtils.isEmpty(paramVo.getKeyword())) {
                    // 1.1 获取标题的高亮属性
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String highlightFields = skuTitle.getFragments()[0].string();
                    // 1.2 设置文本高亮
                    esModel.setSkuTitle(highlightFields);
                }
                esModels.add(esModel);
            }
        }
        result.setProducts(esModels);

        // 2.当前所有商品涉及到的所有属性信息
        ArrayList<SearchResultVo.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attrAgg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            SearchResultVo.AttrVo attrVo = new SearchResultVo.AttrVo();
            // 2.1 得到属性的id
            attrVo.setAttrId(bucket.getKeyAsNumber().longValue());
            // 2.2 得到属性的名字
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrName);
            // 2.3 得到属性的所有值
            List<String> attrValue = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(Collectors.toList());
            attrVo.setAttrValue(attrValue);
            attrVos.add(attrVo);
        }
        result.setAttrs(attrVos);

        // 3.当前所有商品涉及到的所有品牌信息
        ArrayList<SearchResultVo.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brandAgg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            SearchResultVo.BrandVo brandVo = new SearchResultVo.BrandVo();
            // 3.1 得到品牌的id
            long brandId = bucket.getKeyAsNumber().longValue();
            brandVo.setBrandId(brandId);
            // 3.2 得到品牌的名
            String brandName = ((ParsedStringTerms) bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);
            // 3.3 得到品牌的图片
            String brandImg = ((ParsedStringTerms) (bucket.getAggregations().get("brand_img_agg"))).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);
            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);

        // 4.当前商品所有涉及到的分类信息
        ParsedLongTerms catalogAgg = response.getAggregations().get("catalog_agg");
        List<SearchResultVo.CatalogVo> catalogVos = new ArrayList<>();
        for (Terms.Bucket bucket : catalogAgg.getBuckets()) {
            // 设置分类id
            SearchResultVo.CatalogVo catalogVo = new SearchResultVo.CatalogVo();
            catalogVo.setCatalogId(Long.parseLong(bucket.getKeyAsString()));
            // 得到分类名
            ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);
        // ================以上信息从聚合信息中获取
        // 5.分页信息-页码
        result.setPageNum(paramVo.getPageNum());

        // 总记录数
        long total = hits.getTotalHits().value;

        result.setTotal(total);

        // 总页码：计算得到
        int totalPages = (int) (total / EsConstant.PRODUCT_PAGE_SIZE + 0.999999999999);
        result.setTotalPages(totalPages);
        // 设置导航页
        ArrayList<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

        // 6.构建面包屑导航功能
        if(paramVo.getAttrs() != null){
            List<SearchResultVo.NavVo> navVos = paramVo.getAttrs().stream().map(attr -> {
                SearchResultVo.NavVo navVo = new SearchResultVo.NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                R r = productFeignService.getAttrsInfo(Long.parseLong(s[0]));
                // 将已选择的请求参数添加进去 前端页面进行排除
                result.getAttrIds().add(Long.parseLong(s[0]));
                if(r.getCode() == 0){
                    AttrResponseVo data = r.getData(new TypeReference<AttrResponseVo>(){});
                    navVo.setName(data.getAttrName());
                }else{
                    // 失败了就拿id作为名字
                    navVo.setName(s[0]);
                }
                // 拿到所有查询条件 替换查询条件
                String replace = replaceQueryString(paramVo, attr, "attrs");
                navVo.setLink("http://search.praymall.com/list.html?" + replace);
                return navVo;
            }).collect(Collectors.toList());
            result.setNavs(navVos);
        }

        // 品牌、分类
        if (paramVo.getBrandId() != null && paramVo.getBrandId().size() > 0) {
            List<SearchResultVo.NavVo> navs = result.getNavs();
            SearchResultVo.NavVo navVo = new SearchResultVo.NavVo();
            navVo.setName("品牌");
            // TODO 远程查询所有品牌
            R r = productFeignService.brandInfo(paramVo.getBrandId());
            if(r.getCode() == 0){
                List<BrandVo> brand = r.getData(new TypeReference<List<BrandVo>>() {});
                StringBuilder builder = new StringBuilder();
                // 替换所有品牌ID
                String replace = "";
                for (BrandVo brandVo : brand) {
                    builder.append(brandVo.getBrandName()).append(";");
                    replace = replaceQueryString(paramVo, brandVo.getBrandId() + "", "brandId");
                }
                navVo.setNavValue(builder.toString());
                navVo.setLink("http://search.praymall.com/list.html?" + replace);
            }
            navs.add(navVo);
        }
        return result;
    }

    /**
     * 替换字符
     * key ：需要替换的key
     */
    private String replaceQueryString(SearchParamVo paramVo, String value, String key) {
        String encode = null;
        try {
            encode = URLEncoder.encode(value, "UTF-8");
            // 浏览器对空格的编码和java的不一样
            encode = encode.replace("+", "%20");
            encode = encode.replace("%28", "(").replace("%29", ")");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return paramVo.get_queryString().replace("&" + key + "=" + encode, "");
    }

    /**
     * 构建检索请求
     * 模糊匹配，过滤（按照属性，分类，品牌，价格区间，库存），排序，分页，高亮，聚合分析
     *
     * @return 检索请求
     */
    private SearchRequest buildSearchRequest(SearchParamVo searchParamVo) {
        // SearchSourceBuilder用来构建DSL语句的
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // ************************************查询 -> 模糊匹配，过滤（按照属性，分类，品牌，价格区间，库存）
        // 1、构建bool-query
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 1.1、must
        if (!StringUtils.isEmpty(searchParamVo.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", searchParamVo.getKeyword()));
        }
        // 1.2 bool-filter - 按照三级分类id查询
        if (searchParamVo.getCatalog3Id() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", searchParamVo.getCatalog3Id()));
        }

        // 1.3 bool-filter - 按照品牌id查询
        if (searchParamVo.getBrandId() != null && searchParamVo.getBrandId().size() > 0) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", searchParamVo.getBrandId()));
        }

        // 1.4 bool-filter - 按照是否有库存进行查询
        boolQuery.filter(QueryBuilders.termQuery("hasStock", searchParamVo.getHasStock() == 1));

        // 1.5 bool-filter - 按照价格区间进行检索
        if (!StringUtils.isEmpty(searchParamVo.getSkuPrice())) {
            // 1_500/_500/500_
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] strArr = searchParamVo.getSkuPrice().split("_");
            if (strArr.length == 2) {
                // 价格区间，大于xxx小于xxx
                rangeQuery.gte(strArr[0]).lte(strArr[1]);
            } else if (strArr.length == 1) {
                if (searchParamVo.getSkuPrice().startsWith("_")) {
                    // 小于xxx
                    rangeQuery.lte(strArr[0]);
                } else if (searchParamVo.getSkuPrice().endsWith("_")) {
                    // 大于xxx
                    rangeQuery.gte(strArr[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }

        // 1.5 bool-filter - 按照属性进行查询, nested嵌入式查询
        if (searchParamVo.getAttrs() != null && searchParamVo.getAttrs().size() > 0) {
            // attrs=1_5.2英寸:5.5英寸&attrs=2_6G:8G
            for (String attrStr : searchParamVo.getAttrs()) {
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                // attrs=1_5.2英寸:5.5英寸
                String[] strArr = attrStr.split("_");
                String attrId = strArr[0];
                String[] attrValues = strArr[1].split(":");
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                // 每一个都必须生成一个nested查询
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }

        // 封装所有的查询条件
        searchSourceBuilder.query(boolQuery);

        // ************************排序，分页，高亮
        // 排序
        // 1.排序
        if (!StringUtils.isEmpty(searchParamVo.getSort())) {
            String sort = searchParamVo.getSort();
            // sort=hotScore_asc/desc
            String[] s = sort.split("_");
            SortOrder order = "asc".equalsIgnoreCase(s[1]) ? SortOrder.ASC : SortOrder.DESC;
            searchSourceBuilder.sort(s[0], order);
        }

        // 2.分页，pageSize: 5
        searchSourceBuilder.from((searchParamVo.getPageNum() - 1) * EsConstant.PRODUCT_PAGE_SIZE);
        searchSourceBuilder.size(EsConstant.PRODUCT_PAGE_SIZE);

        // 3.高亮
        if (!StringUtils.isEmpty(searchParamVo.getKeyword())) {
            HighlightBuilder builder = new HighlightBuilder();
            builder.field("skuTitle");
            builder.preTags("<b style='color:red'>");
            builder.postTags("</b>");
            searchSourceBuilder.highlighter(builder);
        }


        // *******************聚合分析
        // 1.品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg");
        brandAgg.field("brandId").size(50);
        // 1.1 品牌聚合的子聚合
        brandAgg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brandAgg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        searchSourceBuilder.aggregation(brandAgg);

        // 2.分类聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalogAgg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        searchSourceBuilder.aggregation(catalogAgg);

        // 3.属性聚合
        NestedAggregationBuilder nestedAgg = AggregationBuilders.nested("attr_agg", "attrs");
        // 聚合出当前所有的attrId
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        // 聚合分析出当前attrId对应的attrName
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        // 聚合分析出当前attrId对应的attrValue 这里的属性值可能会有很多 所以写50
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        nestedAgg.subAggregation(attrIdAgg);
        searchSourceBuilder.aggregation(nestedAgg);

        log.info("构建的DSL：" + searchSourceBuilder);
        return new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, searchSourceBuilder);
    }
}
